import { login, logout, getUserInfo } from '@/api/login'
import { setToken, removeToken } from '@/utils/auth'

const userinfo = {
  id: null,
  name: null,
  status: null,
  username: null,
  orgId: null,
  orgName: null,
  phone: null
}

export default {
  namespaced: true,
  state: {
    userinfo,
    role: [],
    rolename: []
  },
  mutations: {
    SET_USERINFO(state, userinfo) {
      state.userinfo = userinfo
    },
    SET_ROLE(state, roles) {
      state.role = roles.map(i => i.slug)
      state.rolename = roles.map(i => i.name)
    }
  },
  actions: {
    login({ dispatch }, loginForm) {
      return login(loginForm).then(res => {
        const { token, expire } = res.data
        setToken(token, expire)
        dispatch('getUserInfo')
      })
    },
    logout({ commit }) {
      return logout().then(() => {
        removeToken()
        commit('SET_USERINFO', userinfo)
        commit('SET_ROLE', [])
      })
    },
    async getUserInfo({ commit }) {
      const { data } = await getUserInfo()
      if (data.roles) {
        commit('SET_ROLE', data.roles)
        delete data.roles
      }
      commit('SET_USERINFO', data)
    }
  }
}
